<?php
class Tools_Utilsareas
{
    /**
     * 字符串截取函数.
     *
     * @param string $str
     * @param int $len
     * @param string $ext
     * @return string
     */
    public static function _substr($str, $len, $ext = '...')
    {
        $length = strlen($str);
        if($length <= $len)
        {
            return $str;
        }
        return mb_strcut($str, 0, $len - strlen($ext)) . $ext;
    }

    /**
     * 以某个字段为KEY重建数组.
     *
     * @param array $arr
     * @param $key
     * @return array
     */
    public static function indexPull(Array $arr, $key)
    {
        $ret = array();
        foreach($arr as $info)
        {
            if(isset($info[$key]))
            {
                $ret[$info[$key]] = $info;
            }
        }
        return $ret;
    }

    /**
     * 以某个字段为KEY重建二维数组.
     *
     * @param array $arr
     * @param $key
     * @return array
     */
    public static function indexPullArray(Array $arr, $key)
    {
        $ret = array();
        foreach($arr as $info)
        {
            if(isset($info[$key]))
            {
                $ret[$info[$key]][] = $info;
            }
        }
        return $ret;
    }

    /**
     * 取出数组中的某个字段信息.
     *
     * @param array $arr
     * @param $key
     * @return array
     */
    public static function arrayDump(Array $arr, $key)
    {
        $ret = array();
        foreach($arr as $info)
        {
            if(isset($info[$key]))
            {
                $ret[] = $info[$key];
            }
        }
        return array_unique($ret);
    }

    /**
     * 按某一字段合并数组.
     *
     * @param array $arr1
     * @param array $_
     * @param string $key
     * @return bool|mixed
     */
    public static function arrayMergeByKey(Array $arr1, Array $_, $key='id')
    {
        $args = func_get_args();
        $key = array_pop($args);
        if(!is_string($key)) return false;
        $arr = array_shift($args);

        foreach($args as &$info)
        {
            $info = self::indexPull($info, $key);
        }

        foreach($arr as $k => &$info)
        {
            $id = $info[$key];
            $tmp = array();
            foreach($args as $v)
            {
                if(!isset($v[$id]))
                {
                    unset($arr[$k]);
                    continue;
                }
                $tmp = array_merge($tmp, $v[$id]);
            }
            $info = array_merge($info, $tmp);
        }
        return $arr;
    }

    static public function toGbk($s)
    {
        if(is_array($s))
        {
            return array_map('self::toGbk', $s);
        }
        return iconv('utf-8', 'gbk', $s);
    }

    static public function toUtf8($s)
    {/*{{{*/
        if(is_array($s))
        {
            return array_map('self::toUtf8', $s);
        }
        return iconv('gbk', 'utf-8', $s);
    }/*}}}*/

    /**
     * 生成翻页代码.
     *
     * @param $total
     * @param $page_id
     * @param $pagesize
     * @param $url
     * @return string
     */
    public static function getPageHtml($total, $page_id, $pagesize = 18, $url = '')
    {/*{{{*/
        $pages      = ceil($total / $pagesize);
        $arr_return = array();
        if($page_id > 1) {
            $arr_return[]   = '<a href="'.$url.($page_id-1).'" class="prev"><em>«上一页</em></a>';
        } else {
            $arr_return[]   = '<a href="javascript:void(0);" class="prev page-blank"><em>«上一页</em></a>';
        }

        if(1 == $page_id) {
            $arr_return[]   = '<span class="cur"><em>1</em></span>';
        } else {
            $arr_return[]   = '<a href="'.$url.'1'.'"><em>1</em></a>';
        }
        $start  = ($page_id - 2);
        if(($pages - $page_id) < 4)
        {
            $start  = ($pages - 4);
        }
        if($start < 2)
        {
            $start  = 2;
        }
        $end    = $start + 4;
        if($end > $pages) {
            $end    = $pages - 1;
        }
        $out_page_id    = $start;
        for($i=1; $i<6; $i++) {
            if($out_page_id == $pages) {
                break;
            }
            if($out_page_id > $end) {
                break;
            }
            if($i == 1) {
                if($out_page_id != 2) {
                    //$arr_return[] = '<span class="page-numbers dots">&hellip;</span>';
                    $arr_return[]   = '<a href="javascript:void(0);" class="page-blank"><em>...</em></a>';
                } else {
                    $i++;
                }
            }

            if($out_page_id == $page_id) {
                $arr_return[]   = '<span class="cur"><em>'.$out_page_id.'</em></span>';
            } else {
                $arr_return[]   = '<a href="'.$url.$out_page_id.'"><em>'.$out_page_id.'</em></a>';
            }
            $out_page_id++;

        }
        //exit;
        if($out_page_id<$pages) {
            //$arr_return[]     = '<span class="page-numbers dots">&hellip;</span>';
            $arr_return[]   = '<a href="javascript:void(0);" class="page-blank"><em>...</em></a>';
        }
        if($pages > 1) {
            if($pages == $page_id) {
                $arr_return[]   = '<span class="cur"><em>'.$pages.'</em></span>';
            } else {
                $arr_return[]   = '<a href="'.$url.$pages.'"><em>'.$pages.'</em></a>';
            }
        }
        if($page_id < $pages) {
            $arr_return[]       = '<a href="'.$url.($page_id+1).'" class="next"><em>下一页»</em></a>';
        } else {
            $arr_return[]   = '<a href="javascript:void(0);" class="next page-blank"><em>下一页»</em></a>';
        }

        $str_return = implode('', $arr_return);
        if($pages < 2)
        {
            $str_return = "";
        }
        return '<div class="page"><fieldset><legend>分页</legend>'.$str_return.'</fieldset></div>';
    }/*}}}*/

    /**
     * Valid Email
     * @access  public
     * @param   string
     * @return  bool
     */
    public static function valid_email($str)
    {/*{{{*/
        return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? false : true;
    }/*}}}*/

    /**
     * 字符串转义.
     * @param $obj
     * @return string
     */
    public static function htmlspecialchars($obj)
    {/*{{{*/
        if(is_string($obj))
        {
            return htmlspecialchars($obj);
        }
        else if(is_array($obj))
        {
            foreach($obj as &$v)
            {
                $v = self::htmlspecialchars($v);
            }
        }
        return $obj;
    }/*}}}*/

    public static function curl_query($pushurl = '', $data = '')
    {/*{{{*/
        $max_retry_times = 3;//curl 重试次数
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_URL, $pushurl);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        $errno = curl_errno($ch);
        $retrys = 0;
        while($errno && $retrys < $max_retry_times)
        {
            ++$retrys;
            $result = curl_exec($ch);
            $errno = curl_errno($ch);
            if (!$errno) break;
        }
        curl_close($ch);
        return $result;
    }/*}}}*/

    /**
     * 截取字符窜  无乱码
     */
    public static function utf8_substr( $str , $start , $length=null )
    {/*{{{*/
        // 先正常截取一遍.
        $res = substr( $str , $start , $length );
        $strlen = strlen( $str );

        /* 接着判断头尾各6字节是否完整(不残缺) */
        // 如果参数start是正数
        if ( $start >= 0 )
        {
            // 往前再截取大约6字节
            $next_start = $start + $length; // 初始位置
            $next_len = $next_start + 6 <= $strlen ? 6 : $strlen - $next_start;
            $next_segm = substr( $str , $next_start , $next_len );

            // 如果第1字节就不是 完整字符的首字节, 再往后截取大约6字节
            $prev_start = $start - 6 > 0 ? $start - 6 : 0;
            $prev_segm = substr( $str , $prev_start , $start - $prev_start );
        }
        else
        {
            // start是负数
            // 往前再截取大约6字节
            $next_start = $strlen + $start + $length; // 初始位置
            $next_len = $next_start + 6 <= $strlen ? 6 : $strlen - $next_start;
            $next_segm = substr( $str , $next_start , $next_len );

            // 如果第1字节就不是 完整字符的首字节, 再往后截取大约6字节.
            $start = $strlen + $start;
            $prev_start = $start - 6 > 0 ? $start - 6 : 0;
            $prev_segm = substr( $str , $prev_start , $start - $prev_start );
        }

        // 判断前6字节是否符合utf8规则
        if ( preg_match( '@^([\x80-\xBF]{0,5})[\xC0-\xFD]?@' , $next_segm , $bytes ) )
        {
            if ( !empty( $bytes[1] ) ){
                $bytes = $bytes[1];
                $res .= $bytes;
            }
        }

        // 判断后6字节是否符合utf8规则
        $ord0 = ord( $res[0] );
        if ( 128 <= $ord0 && 191 >= $ord0 )
        {
            // 往后截取 , 并加在res的前面.
            if ( preg_match( '@[\xC0-\xFD][\x80-\xBF]{0,5}$@' , $prev_segm , $bytes ) )
            {
                if ( !empty( $bytes[0] ) )
                {
                    $bytes = $bytes[0];
                    $res = $bytes . $res;
                }
            }
        }
        return $res;
    }/*}}}*/

    /**
     * 获取日期数组
     * @param $start
     * @param $end
     * @param string $order
     * @param int $dperiod
     * @return array
     */
    public static function getdays($start, $end, $order = 'asc', $dperiod = 4) {
        $dtimes = array();
        if($start > $end || !$dperiod) return $dtimes;
        if($dperiod == 8) $w = date('N', strtotime($end))-1;
        $n = 0;
        while(1) {
            if($dperiod == 16) {
                $dtime = date('Y-m-01', strtotime($end.' -'.$n.' month'));
            } else if($dperiod == 8) {
                $dtime = date('Y-m-d', strtotime($end.'-'.$w.' day -'.$n.' week'));
            } else if($dperiod == 4) {
                $dtime = date('Y-m-d', strtotime($end.' -'.$n.' day'));
            } else {
                break;
            }
            if($dtime < $start) break;
            $dtimes[$n++] = $dtime;
        }
        if($dperiod > 4) unset($dtimes[0]);
        if ($order == 'asc') sort($dtimes);
        return $dtimes;
    }

    public static function changeKey($array, $oldkey, $newkey)
    {
        foreach ($array as $key => &$value)
        {
            $value[$newkey] = $value[$oldkey];
            unset($value[$oldkey]);
        }
        return $array;
    }

    public static function changeKeyArray($array, $changearray)
    {
        foreach ($array as $key => &$value)
        {
            foreach ($changearray as $changek => $changev)
            {
                $value[$changev] = $value[$changek];
                unset($value[$changek]);
            }
        }
        return $array;
    }

    /**
     * 判断是否为手机端请求
     * @return bool
     */
    public static function is_mobile()
    {
        //正则表达式,批配不同手机浏览器UA关键词。
        $regex_match="/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";
        $regex_match.="htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|"; $regex_match.="blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";
        $regex_match.="symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";
        $regex_match.="jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";
        $regex_match.=")/i";
        return isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']) or preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT']));
        //如果UA中存在上面的关键词则返回真。
    }

    /** 二维数据根据某字段排序
     * @param $list
     * @param $field
     * @param string $sortby
     * @return array|bool
     */
    public static function list_sort_by($list, $field, $sortby = 'asc')
    {
        if (is_array($list))
        {
            $refer = $resultSet = array();
            foreach ($list as $i => $data)
            {
                $refer[$i] = &$data[$field];
            }
            switch ($sortby)
            {
                case 'asc': // 正向排序
                    asort($refer);
                    break;
                case 'desc': // 逆向排序
                    arsort($refer);
                    break;
                case 'nat': // 自然排序
                    natcasesort($refer);
                    break;
            }
            foreach ($refer as $key => $val)
            {
                $resultSet[] = &$list[$key];
            }
            return $resultSet;
        }
        return false;
    }
    
    public static function getArrayTree (Array $datas)
    {
        $tree = array ();
        //第一步，将分类id作为数组key,并创建children单元
        foreach ( $datas as $data )
        {
            $tree[ $data[ 'id' ] ]               = $data;
            $tree[ $data[ 'id' ] ][ 'children' ] = array ();
        }
      
        //第二步，利用引用，将每个分类添加到父类children数组中，这样一次遍历即可形成树形结构。
        foreach ( $tree as $key => $item )
        {
            if ( $item[ 'pid' ] != 0 )
            {
                $tree[ $item[ 'pid' ] ][ 'children' ][] = &$tree[ $key ]; //注意：此处必须传引用否则结果不对
                if ( $tree[ $key ][ 'children' ] == null )
                {
                    unset ( $tree[ $key ][ 'children' ] ); //如果children为空，则删除该children元素（可选）
                }
            }
        }
       
        ////第三步，删除无用的非根节点数据
        foreach ( $tree as $key => $data )
        {
           
            if ( $data[ 'pid' ] != 0 )
            {
                unset ( $tree[ $key ] );
            }
        }
         return $tree;
    }

}/*}}}*/
